package com.eien.phonezwei.broadcast;

import java.util.ArrayList;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.CallLog;
import android.provider.CallLog.Calls;
import android.provider.ContactsContract;
import android.telephony.PhoneStateListener;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.eien.phonezwei.service.PhoneZweiService;

public class PhoneCallReceiver extends BroadcastReceiver {

	Context eContext;
	SharedPreferences eSharedPreferences;

	@Override
	public void onReceive(Context context, Intent intent) {
		Log.i("PhoneCallReceiver", "" + intent.getAction());
		eContext = context;
		eSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
		if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
			// 如果是去电（拨出），不执行动作
		} else if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
			// 收到短信
			if (eSharedPreferences.getBoolean("forwardSMS", false)) {
				StringBuilder sb_sms = new StringBuilder();
				Bundle bundle = intent.getExtras();
				if (bundle != null) {
					// 将带有puds字符串特征的对象取出
					Object[] myOBJpdus = (Object[]) bundle.get("pdus");
					SmsMessage[] messages = new SmsMessage[myOBJpdus.length];
					for (int i = 0; i < myOBJpdus.length; i++) {
						// 通过SmsMessage.createFromPdu()方式取出短信文字
						messages[i] = SmsMessage.createFromPdu((byte[]) myOBJpdus[i]);
					}
					for (SmsMessage currentMessage : messages) {
						String MsgNumber = currentMessage.getDisplayOriginatingAddress();
						String contact = getContactNameFromPhoneNum(MsgNumber);
						sb_sms.append(contact);
						sb_sms.append(MsgNumber);
						sb_sms.append(": ");
						// 短信内容
						sb_sms.append(currentMessage.getDisplayMessageBody());
					}
				}
				String msg_sms = sb_sms.toString();
				Log.i("PhoneCallReceiver", "转发短信 msg_sms=" + msg_sms);
				String sendToNumber = eSharedPreferences.getString("sendToNumber", "");
				if (sendToNumber.equals("")) {
					Toast.makeText(eContext, "转发失败，目标手机号码不能为空！", Toast.LENGTH_LONG).show();
				} else {
					doSendSMS(sendToNumber, msg_sms);
				}
			}
		} else {
			// 查了下android文档，貌似没有专门用于接收来电的action,所以，非去电即来电
			// if (eSharedPreferences.getBoolean("forwardMissedCall", false)) {
				TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
				tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
				// 设置一个监听器
			// }
		}

	}

	// 手机状态监听器
	PhoneStateListener listener = new PhoneStateListener() {
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			// state 当前状态 incomingNumber,貌似没有去电的API
			super.onCallStateChanged(state, incomingNumber);
			switch (state) {
			case TelephonyManager.CALL_STATE_RINGING:
				// System.out.println("响铃:来电号码" + incomingNumber);
				Log.i("PhoneCallReceiver", "listener 响铃:来电号码" + incomingNumber);
				// 如果来电号码和转发目标号码相同，开启转发服务，用于没带手机并且忘记开服务的情况
				if (eSharedPreferences.getString("sendToNumber", "").equals(incomingNumber)) {
					SharedPreferences.Editor mEditor = eSharedPreferences.edit();
					mEditor.putBoolean("forwardMissedCall", true);
					mEditor.putBoolean("forwardSMS", true);
					mEditor.commit();
				}
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK:
				// System.out.println("接听");
				Log.i("PhoneCallReceiver", "listener 接听");
				break;
			case TelephonyManager.CALL_STATE_IDLE:
				// System.out.println("挂断");
				Log.i("PhoneCallReceiver", "listener 挂断");
				if (eSharedPreferences.getBoolean("forwardMissedCall", false)) {
					if ((eSharedPreferences.getBoolean("contactOnly", false)) && getContactNameFromPhoneNum(incomingNumber).equals("")) {
						// System.out.println(incomingNumber+"不是联系人号码，不转发");
						Log.i("PhoneCallReceiver", "listener " + incomingNumber + "不是联系人号码，不转发");
					} else {
						// System.out.println("开始转发来自" + incomingNumber + "的未接来电");
						Log.i("PhoneCallReceiver", "listener 开始转发来自" + incomingNumber + "的未接来电");
						new Handler().postDelayed(new Runnable() {
							@Override
							public void run() {
								int missedCall = readMissCall(eContext);
								if (missedCall > 0) {
									// System.out.println(eServiceSended + "未接电话：" + missedCall);
									Intent serviceIntent = new Intent(eContext, PhoneZweiService.class);
									serviceIntent.setAction("com.eien.phonezwei.service.PhoneZweiService");
									eContext.startService(serviceIntent);
								}
							}
						}, 2000);
					}
				}
				break;
			}
		}
	};

	/**
	 * 获取未接来电数量
	 * 
	 * @param context
	 * @return
	 */
	private int readMissCall(Context context) {
		int result = 0;
		Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI, new String[] { Calls.TYPE }, " type=? and new=?",
				new String[] { Calls.MISSED_TYPE + "", "1" }, "date desc");

		if (cursor != null) {
			result = cursor.getCount();
			cursor.close();
		}
		return result;
	}

	/**
	 * 发送短信的方法
	 * 
	 * @param sendToNumber
	 * @param msg
	 */
	private void doSendSMS(String sendToNumber, String msg) {
		if (msg != null) {
			SmsManager sms = SmsManager.getDefault();
			ArrayList<String> texts = sms.divideMessage(msg);
			if (texts.size() <= 1) {
				sms.sendTextMessage(sendToNumber, null, msg, null, null);
			} else if (texts.size() > 1) {
				sms.sendMultipartTextMessage(sendToNumber, null, texts, null, null);
			}
			Toast.makeText(eContext, "转发至: " + sendToNumber, Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 根据号码从通讯录得到联系人信息
	 * 
	 * @param context
	 * @param phoneNum
	 * @return
	 */
	public String getContactNameFromPhoneNum(String phoneNum) {
		String contactName = "";
		ContentResolver cr = eContext.getContentResolver();
		try {
			Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.NUMBER + " = ?",
					new String[] { phoneNum }, null);
			if (pCur.moveToFirst()) {
				contactName = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
				pCur.close();
			}
		} catch (Exception e) {
			System.out.println(e.toString());
		}

		return contactName;
	}
}
